import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 用户信息接口
interface UserInfo {
  id: string
  username: string
  avatar: string
  email: string
  phone: string
  role: 'admin' | 'user' | 'guest'
  permissions: string[]
  lastLoginTime: string
}

// 用户状态管理
export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const isLoggedIn = ref<boolean>(false)
  const loading = ref<boolean>(false)

  // 计算属性
  const isAdmin = computed(() => userInfo.value?.role === 'admin')
  const hasPermission = computed(() => (permission: string) => {
    return userInfo.value?.permissions.includes(permission) || false
  })

  // 登录
  const login = async (username: string, password: string) => {
    loading.value = true
    try {
      // 模拟登录请求
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟登录成功
      const mockUserInfo: UserInfo = {
        id: '1',
        username,
        avatar: 'https://via.placeholder.com/100',
        email: `${username}@example.com`,
        phone: '138****8888',
        role: 'user',
        permissions: ['read', 'write'],
        lastLoginTime: new Date().toISOString()
      }
      
      userInfo.value = mockUserInfo
      token.value = 'mock-token-' + Date.now()
      isLoggedIn.value = true
      
      // 保存到本地存储
      uni.setStorageSync('userInfo', mockUserInfo)
      uni.setStorageSync('token', token.value)
      
      return { success: true, message: '登录成功' }
    } catch (error) {
      return { success: false, message: '登录失败' }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    userInfo.value = null
    token.value = ''
    isLoggedIn.value = false
    
    // 清除本地存储
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('token')
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...newUserInfo }
      uni.setStorageSync('userInfo', userInfo.value)
    }
  }

  // 初始化用户信息
  const initUserInfo = () => {
    try {
      const storedUserInfo = uni.getStorageSync('userInfo')
      const storedToken = uni.getStorageSync('token')
      
      if (storedUserInfo && storedToken) {
        userInfo.value = storedUserInfo
        token.value = storedToken
        isLoggedIn.value = true
      }
    } catch (error) {
      console.error('初始化用户信息失败:', error)
    }
  }

  // 检查权限
  const checkPermission = (permission: string): boolean => {
    return hasPermission.value(permission)
  }

  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,
    loading,
    
    // 计算属性
    isAdmin,
    hasPermission,
    
    // 方法
    login,
    logout,
    updateUserInfo,
    initUserInfo,
    checkPermission
  }
})
